<?php
namespace Home\Controller;

use Think\Controller;
use Think\Model;
use Think\Page;

class OrderController extends CommonController {

    public function test(){
        dump($this->getUserInfo(['sig'=>'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pbiI6ZmFsc2UsImNsYWltcyI6bnVsbCwidWlkIjoiNTg4NjgiLCJ2IjoxLCJpYXQiOjE0OTgyODg1MDF9.qSuMm2_ap03sJnCdB2x_5xRV3hxC-llt24ULQJLccc0']));
    }

    /**
     * 首页
     */
    public function index() {
        $type   = I('type', 1);
        $search = [];

        $uname = I('uname', '');
        if ($uname != '') {
            $search['uname'] = $uname;
        }

        $order_sn = I('order_sn', "");
        if ($order_sn != "") {
            $search['order_sn'] = $order_sn;
        }
        $exchange_type = I('exchange_type', 3);
        if ($exchange_type != 3) {
            $search['exchange_type'] = $exchange_type;
        } elseif ($exchange_type == 3) {
            $search['exchange_type'] = 3;
        }

        $start_time = I('start_time', '');
        if ($start_time != '') {
            $search['start_time'] = $start_time;
        }

        $end_time = I('end_time', '');
        if ($end_time != '') {
            $search['end_time'] = $end_time;
        }

        $data = $this->lists($type, $search);
        $this->assign($data);
        $this->display();
    }

    /**
     * @ActionName 订单列表的方法
     * @param int $type 类型
     * @param array $search 搜索条件
     * @return array 订单订表
     */
    public function lists($type = 1, $search = []) {
        $where['o.seller_id'] = 4;

        if ($type == 1) {
            //1：所有订单
            //没有任何
        } elseif ($type == 10) {
            //10：待付款
            $where['o.order_state'] = 10;
        } elseif ($type == 20) {
            //20：待发货
            $where['o.order_state'] = 20;
        } elseif ($type == 30) {
            //30：待收货
            $where['o.order_state'] = 30;
        } elseif ($type == 40) {
            //40：确认收货
            $where['o.order_state'] = 40;
        } elseif ($type == 50) {
            //50：交易关闭
            $where['o.order_state'] = 50;
        } elseif ($type == 60) {
            //60:已经催单
            $where['o.is_reminder'] = 1;
        } elseif ($type == 70) {
            //70: 有退货
            $where['g.refund_reason'] = array('neq', 0);
        } elseif ($type == 80) {
            //80：有评论
            $where['o.evaluation_status'] = 1;
        }

        if (isset($search['uname'])) {
            $where['a.uname'] = $search['uname'];
        }

        if (isset($search['order_sn'])) {
            $where['o.order_sn'] = $search['order_sn'];
        }

        if (isset($search['exchange_type'])) {
            if ($search['exchange_type'] == 0) {
                $where['o.exchange_type'] = 0;
            } elseif ($search['exchange_type'] == 1) {
                $where['o.exchange_type'] = 1;
            }
        }

        if (isset($search['start_time'])) {
            $where['o.add_time'] = ['gt', strtotime($search['start_time'])];
        }

        if (isset($search['end_time'])) {
            $where['o.add_time'] = ['lt', strtotime($search['start_time'])];
        }


        $field = [
            'o.id'                       => 'order_id',
            'o.order_sn'                 => 'order_order_sn',
            'o.trade_sn'                 => 'order_trade_sn',
            'o.seller_id'                => 'order_seller_id',
            'o.store_id'                 => 'order_store_id',
            'o.store_name'               => 'order_store_name',
            'o.buyer_id'                 => 'order_buyer_id',
            'o.buyer_name'               => 'order_buyer_name',
            'o.add_time'                 => 'order_add_time',
            'o.exchange_type'            => 'order_exchange_type',
            'o.payment_id'               => 'order_payment_id',
            'o.payment_name'             => 'order_payment_name',
            'o.payment_code'             => 'order_payment_code',
            'o.payment_direct'           => 'order_payment_direct',
            'o.payment_time'             => 'order_payment_time',
            'o.pay_message'              => 'order_pay_message',
            'o.refund_approval'          => 'order_refund_approval',
            'o.refund_reason'            => 'order_refund_reason',
            'o.refund_type'              => 'order_refund_type',
            'o.refund_explain'           => 'order_refund_explain',
            'o.refund_amount'            => 'order_refund_amount',
            'o.refund_img'               => 'order_refund_img',
            'o.message'                  => 'order_message',
            'o.shipping_time'            => 'order_shipping_time',
            'o.shipping_express_id'      => 'order_shipping_express_id',
            'o.shipping_code'            => 'order_shipping_code',
            'o.finnshed_time'            => 'order_finnshed_time',
            'o.order_sell_price'         => 'order_order_sell_price',
            'o.order_money'              => 'order_order_money',
            'o.shipping_fee'             => 'order_shipping_fee',
            'o.shipping_name'            => 'order_shipping_name',
            'o.evaluation_status'        => 'order_evaluation_status',
            'o.evaluation_time'          => 'order_evaluation_time',
            'o.evalseller_status'        => 'order_evalseller_status',
            'o.evalseller_time'          => 'order_evalseller_time',
            'o.order_message'            => 'order_order_message',
            'o.order_state'              => 'order_order_state',
            'o.order_pointscount'        => 'order_order_pointscount',
            'o.order_from'               => 'order_order_from',
            'o.deliver_explain'          => 'order_deliver_explain',
            'o.daddress_id'              => 'order_daddress_id',
            'o.user_discount_coupon_ids' => 'order_user_discount_coupon_ids',
            'o.is_reminder'              => 'order_is_reminder',
            'g.id'                       => 'goods_id',
            'g.order_id'                 => 'goods_order_id',
            'g.goods_id'                 => 'goods_goods_id',
            'g.goods_name'               => 'goods_goods_name',
            'g.brand_name'               => 'goods_brand_name',
            'g.goods_spec'               => 'goods_goods_spec',
            'g.goods_price'              => 'goods_goods_price',
            'g.goods_num'                => 'goods_goods_num',
            'g.goods_image'              => 'goods_goods_image',
            'g.goods_returnnum'          => 'goods_goods_returnnum',
            'g.stores_id'                => 'goods_stores_goods_returnnum',
            'g.scale'                    => 'goods_scale',
            'g.or_my_type'               => 'goods_or_my_type',
            'g.express_id'               => 'goods_express_id',
            'g.shipping_code'            => 'goods_shipping_code',
            'g.user_id'                  => 'goods_user_id',
            'g.user_name'                => 'goods_user_name',
            'g.evaluation_status'        => 'goods_evaluation_status',
            'g.refund_approval'          => 'goods_refund_approval',
            'g.refund_reason'            => 'goods_refund_reason',
            'g.refund_type'              => 'goods_refund_type',
            'g.refund_explain'           => 'goods_refund_explain',
            'g.refund_amount'            => 'goods_refund_amount',
            'g.sell_price'               => 'goods_sell_price',
            'g.money'                    => 'goods_money',
            'g.refund_img'               => 'goods_refund_img',
            'g.return_num'               => 'goods_return_num',
            'a.id'                       => 'address_id',
            'a.order_id'                 => 'address_order_id',
            'a.uname'                    => 'address_uname',
            'a.mobile'                   => 'address_mobile',
            'a.province'                 => 'address_province',
            'a.city'                     => 'address_city',
            'a.area'                     => 'address_area',
            'a.address'                  => 'address_address',
            'a.postcode'                 => 'address_postcode',
        ];

        $order = D('Order');

        $groupSql  = $order->where($where)->alias('o')
            ->join('LEFT JOIN  __ORDER_GOODS__ g ON g.order_id = o.id')
            ->join('LEFT JOIN  __ORDER_ADDRESS__ a ON a.order_id = o.id')
            ->group('o.id')->field('count(*)')->buildSql();
        $count     = D()->table("{$groupSql} as t")->count();
        $Page      = new Page($count, 2);
        $orderList = $order->field($field)->where($where)->order('add_time')->limit($Page->firstRow . ',' . $Page->listRows)->alias('o')
            ->join('LEFT JOIN  __ORDER_GOODS__ g ON g.order_id = o.id')
            ->join('LEFT JOIN  __ORDER_ADDRESS__ a ON a.order_id = o.id')
            ->group('o.id')->select();
        foreach ($orderList as $key => $value) {
            $state_name = '';
            switch ($value['order_order_state']) {
                //订单状态：10：待付款 20：待发货 30：待收货 40：确认收货  50：交易关闭
                case 10:
                    $state_name = '待付款';
                    break;
                case 20:
                    $state_name = '待发货';
                    break;
                case 30:
                    $state_name = '待收货';
                    break;
                case 40:
                    $state_name = '确认收货';
                    break;
                case 50:
                    $state_name = '交易关闭';
                    break;
            }
            $orderList[$key]['state_name'] = $state_name;
        }

        $show = $Page->show();// 分页显示输出

        return [
            'page'      => $show,
            'orderList' => $orderList,
            'type'      => $type,
            'search'    => $search
        ];

    }

    /**
     * @Action 评情封装的方法
     * @param $id
     * @return array
     */
    public function detailsfuc($id) {
        $where['seller_id'] = 4;
        $order              = M('Order');
        $orderOne           = $order->find($id);
        if (!$orderOne) {
            $this->redirect('lists');
        }

        //状态
        switch ($orderOne['order_state']) {
            //订单状态：10：待付款 20：待发货 30：待收货 40：确认收货  50：交易关闭
            case 10:
                $state_name = '待付款';
                break;
            case 20:
                $state_name = '待发货';
                break;
            case 30:
                $state_name = '待收货';
                break;
            case 40:
                $state_name = '确认收货';
                break;
            case 50:
                $state_name = '交易关闭';
                break;
        }
        $orderOne['state_name'] = $state_name;
        //地址
        $orderAddress              = M('OrderAddress');
        $this->where['order_id']   = $orderOne['id'];
        $orderOne['order_address'] = $orderAddress->where($where)->find();

        $order_goods_total_sell  = 0;
        $order_goods_total_money = 0;
        //商品
        $orderGoods     = M('OrderGoods');
        $orderGoodsList = $orderGoods->where(['order_id' => $id])->select();
        foreach ($orderGoodsList as $key => $value) {
            $order_goods_total_sell += $value['sell_price'];
            $order_goods_total_money += $value['money'];
            $orderGoodsList[$key]['goods_image'] = C('IMGURL') . '/' . $value['goods_image'];

        }
        $orderOne['order_Goods']             = $orderGoodsList;
        $orderOne['order_Goods_total_sell']  = $order_goods_total_sell;
        $orderOne['order_Goods_total_money'] = $order_goods_total_money;

        $youhuiquan       = $orderOne['user_discount_coupon_ids'];
        $youhuiquan_price = 0;
        foreach (explode(',', $youhuiquan) as $value) {
            if ($value != 'undefined') {
                $id = M('UserDiscountCoupon')->find($value)['discount_coupon_id'];
                if ($id) {
                    $my_discount_coupon = M('DiscountCoupon')->find($id);
                    if ($my_discount_coupon) {

                        $youhuiquan_price += $my_discount_coupon['price'];
                    }
                }
            }
        }

        return [
            'youhuiquan' => $youhuiquan_price,
            'orderOne'   => $orderOne
        ];
    }

    /**
     * 订单详情
     */
    public function details() {
        $orderId = I('get.id', 0);
        //dump($this->detailsfuc($orderId));
        $this->assign($this->detailsfuc($orderId));
        $this->display();
    }

    /**
     * 配货单打印
     */
    public function order_Print() {
        $orderId                 = I('get.id', 0);
        $orderOne                = $this->detailsfuc($orderId);
        $orderOne['businessOne'] = M('Business')->find($orderOne['orderOne']['store_id']);

        $this->assign($orderOne);
        $this->display();
    }

    /**
     * 商品退款审核
     */
    public function refundApproval() {
        $getdata['id']              = I('get.id');
        $getdata['refund_approval'] = I('get.refundApproval');
        M('OrderGoods')->save($getdata);

        $res = M('OrderGoods')->find(I('get.id'));

        die(json_success('', ['id' => I('get.id'), 'refund_approval' => $res['refund_approval']]));

    }

    /**
     * 退款原因的说明
     */
    public function refund_reason() {
        $id  = I('get.id');
        $res = M('OrderGoods')->find($id);
        $this->assign('orderGoodsOne', $res);
        $this->display();
    }

    /**
     * 发货单列表
     */
    public function sendlist() {
        $search = [];

        $uname = I('post.uname', '');
        if ($uname != '') {
            $search['uname'] = $uname;
        }

        $order_sn = I('post.order_sn', "");
        if ($order_sn != "") {
            $search['order_sn'] = $order_sn;
        }
        $exchange_type = I('post.exchange_type', 3);
        if ($exchange_type != 3) {
            $search['exchange_type'] = $exchange_type;
        } elseif ($exchange_type == 3) {
            $search['exchange_type'] = 3;
        }

        $start_time = I('post.start_time', '');
        if ($start_time != '') {
            $search['start_time'] = $start_time;
        }

        $end_time = I('post.end_time', '');
        if ($end_time != '') {
            $search['end_time'] = $end_time;
        }
        $data = $this->lists(20, $search);
        $this->assign($data);
        $this->display();
    }

    /**
     * 删除订单
     */
    public function del() {
        $id       = I("get.id", 0);
        $orderOne = M('order')->find($id);
        if ($orderOne['order_state'] != 50)
            die(json_error('不允许删除'));

        M('order')->delete($id);
        M('order_address')->where(['order_id' => $id])->delete();
        M('order_goods')->where(['order_id' => $id])->delete();
        die(json_success('删除成功'));
    }

    /**
     * 填写物流单号
     */
    public function addShippingCode() {
        $shippingcode = I('post.shipping_code');
        $order_id     = I('post.id');

        $res = M('order')->save([
            'id'            => $order_id,
            'shipping_code' => $shippingcode
        ]);

        M('order')->save([
            'id'=>$order_id,
            'order_state'=>30,
        ]);

        if ($res) {
            echo json_success('快递单号添加成功');
        }
    }

}